package com.ufox.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ufox.entity.*;
import com.ufox.exception.UserException;
import com.ufox.mapper.OrderitemMapper;
import com.ufox.mapper.OrdersMapper;
import com.ufox.mapper.ProductsMapper;
import com.ufox.mapper.UserMapper;
import com.ufox.req.PasswordREQ;
import com.ufox.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ufox.utils.EmailUtil;
import com.ufox.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 优狐科技-www.hbufox.com
 * @since 2022-06-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderitemMapper orderitemMapper;

    @Autowired
    private ProductsMapper productsMapper;

    @Value("${email_url}")
    private String emailUrl;

    @Override
    @Transactional
    public Result regist(User user) {

        user.setStatecode( IdUtil.simpleUUID());
        user.setPassword(  SecureUtil.md5(user.getPassword()));

        try{
            userMapper.insert(user);

            //2 发邮件
            String body = "请点击链接激活用户,如果不能点击把地址复制到浏览器中打开," +emailUrl+
                    "user/active/"+user.getStatecode();

            EmailUtil.sendEmail("1962319910@qq.com","xcutjlrbqizscjed",
                    user.getEmail(),"我的京东激活邮件",body);
            return Result.ok("注册成功","");
        }catch (Exception e){
            throw new RuntimeException("发送邮件失败");
        }
    }

    @Override
    public void updateUserByCode(String statecode) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getStatecode,statecode);
        User user = userMapper.selectOne(wrapper);
        if(user == null){
            throw new UserException("该用户不存在");
        }else if(user.getState() == 1){
            throw new UserException("该用户已经激活");
        }else if(System.currentTimeMillis() - user.getRegtime().getTime() > 1000L*3600 ){
            //过期
            userMapper.deleteById(user.getId());
            throw new UserException("激活邮件已经失效!请重新注册");
        }else{
            user.setState(1);
            userMapper.updateById(user);
        }
    }

    @Override
    @Transactional
    public List<Orders> getOrdersByUserId(String userId) {

        //用户id
        //1 查询用户订单
        //2 为每一个订单的items赋值
        //3 为每一个item 的product赋值
//        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Orders::getUserId,userId);
//        List<Orders> orders = OrdersMapper.selectList(queryWrapper);
        List<Orders> orders = ordersMapper.findAll(userId);

        User user = userMapper.selectById(userId);

        for(Orders order:orders){
            LambdaQueryWrapper<Orderitem> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Orderitem::getOrderId,order.getId());
            List<Orderitem> items = orderitemMapper.selectList(wrapper);

            for(Orderitem item:items){
                Products prod = productsMapper.selectProdAndUser(item.getProdId());
                item.setProducts(prod);
                order.setUserName(user.getNickname());
            }
            order.setOrderItems(items);
        }

        return orders;


    }

    @Override
    public Result getCustOrdersByUserId(String userId) {
        //用户id
        //1 查询用户商品
        //2 根据商品id查订单项
        LambdaQueryWrapper<Products> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Products::getUserId,userId);
        List<Products> products = productsMapper.selectList(wrapper);
        for (Products product : products) {
            LambdaQueryWrapper<Orderitem> w = new LambdaQueryWrapper<>();
            w.eq(Orderitem::getProdId,product.getId());
            List<Orderitem> orderitems = orderitemMapper.selectList(w);
            product.setOrderitems(orderitems);
            for (Orderitem orderitem : orderitems) {
                LambdaQueryWrapper<Orders> ww = new LambdaQueryWrapper<>();
                ww.eq(Orders::getId,orderitem.getOrderId());
                List<Orders> list = ordersMapper.selectList(ww);
                orderitem.setList(list);
            }
        }

//        List<Orders> list =  userMapper.getCustOrdersByUserId(userId);
        return Result.ok(products);
    }

    @Override
    @Transactional
    public Result updatePassword(PasswordREQ req) {
        if (req == null || StringUtils.isEmpty(req.getPassword())) {
            return Result.error("新密码不能为空");
        }
        // 更新密码
        User user = baseMapper.selectById(req.getUserId());
        user.setPassword(MD5Util.getMD5String(req.getPassword()));
        baseMapper.updateById(user);
        Result result = Result.ok();
        result.setMessage("修改成功");
        return result;
    }

    @Override
    @Transactional
    public Result checkPassword(PasswordREQ req) {
        if (req == null || StringUtils.isEmpty(req.getPassword())) {
            return Result.error("原密码不能为空");
        }
        User user = baseMapper.selectById(req.getUserId());
        MD5Util.getMD5String(req.getPassword());
        String password = user.getPassword();

        Result result = Result.ok();
        if (!password.equals(MD5Util.getMD5String(req.getPassword()))) {
            result.setFlag(false);
        }else{
            result.setFlag(true);
        }
        return result;
    }
}
